package com.nowcoder.community.controller;

import com.nowcoder.community.annotation.LoginRequired;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.FollowService;
import com.nowcoder.community.service.LikeService;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.CommunityUtil;
import com.nowcoder.community.util.HostHolder;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Path;

import static com.nowcoder.community.util.CommunityConstant.ENTITY_TYPE_USER;

@Controller
@RequestMapping("/user")
public class UserController implements CommunityConstant {

    private Logger logger = LoggerFactory.getLogger(UserController.class);

    //注入上传文件路径
    @Value("${community.path.upload}")
    private String uploadPath;

    //注入域名
    @Value("${community.path.domain}")
    private String domain;

    //注入项目名
    @Value("${server.servlet.context-path}")
    private String contextPath;

    //注入Userservice
    @Autowired
    private UserService userService;

    //修改的是当前线程的用户的头像地址
    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private LikeService likeService;

    @Autowired
    private FollowService followService;

    /**
     * 获取账号设置页面
     */
    @LoginRequired
    @RequestMapping(path = "setting",method = RequestMethod.GET)
    public String getSettingPage(){
        return "/site/setting";
    }

    /**
     * 上传头像
     */
    @LoginRequired
    @RequestMapping(path = "/upload" , method = RequestMethod.POST)
    public String uploadHeader(MultipartFile headerImage, Model model){  //如果接受的是多个文件，则使用MultipartFile数组接受
        //异常处理： 空置处理
        if(headerImage == null){
            //向浏览器返回错位信息
            model.addAttribute("error","您还没有上传图片");
            return "/site/setting";
        }

        //重命名文件，避免文件覆盖
        //获取原文件名
        String fileName = headerImage.getOriginalFilename();
        //截取文件名后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //空值异常处理
        if (StringUtils.isBlank(suffix)) {
            //向浏览器返回错位信息
            model.addAttribute("error","文件格式不正确");
            return "/site/setting";
        }

        //生成随机文件名
        fileName = CommunityUtil.generateUUID()+suffix;
        //确定文件存放路径
        File dest = new File(uploadPath+"/"+fileName);

        try {
            //将图片内容写入文件
            headerImage.transferTo(dest);
        } catch (IOException e) {
            //记录错误日志
            logger.error("上传文件失败"+e.getMessage());
            //抛出异常
            throw new RuntimeException("上传文件失败，服务器发生异常",e);
        }

        //跟更新当前用户的头像地址(Web访问路径)
        //http://localhost:8080/community/user/header/xx.png
        //获得当前用户
        User user = hostHolder.getUser();
        //拼接头像路径
        String headerUrl = domain+contextPath+"/user/header/"+fileName;
        //更新地址
        userService.updateHeader(user.getId(),headerUrl);

        return "redirect:/index";
    }

    /**
     * 获取头像
     */

    @RequestMapping(path = "/header/{fileName}", method = RequestMethod.GET)
    public void getHeader(@PathVariable("fileName") String fileName, HttpServletResponse response) {
        //返回的是图形类型，Java没有这种类型，使用response返回，所以返回数据类型为空
        //获取服务器文件存放路径
        fileName = uploadPath+"/"+fileName;
        //获取文件后缀名，以便确定响应内容的类型
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //响应图片
        //1.设置响应类型
        response.setContentType("image/"+suffix);
        try (
                //2.1获取响应的字节流输出流
                OutputStream os =response.getOutputStream();
                //2.2获取文件的输入流
                FileInputStream is = new FileInputStream(fileName);
                ){
            //声明一个缓冲区。一批一批输出
            byte [] buffer = new byte[1024];
            //声明游标
            int b = 0;
            //不断输出
            while((b = is.read(buffer)) != -1){
                os.write(buffer,0,b);
            }

        } catch (IOException e) {
            logger.error("获取头像失败"+e.getMessage());
        }
    }

    // 个人主页
    @RequestMapping(path = "/profile/{userId}", method = RequestMethod.GET)
    public String getProfilePage(@PathVariable("userId") int userId, Model model) {
        User user = userService.findUserById(userId);
        if (user == null) {
            throw new RuntimeException("该用户不存在!");
        }

        // 用户
        model.addAttribute("user", user);
        // 点赞数量
        int likeCount = likeService.findUserLikeCount(userId);
        model.addAttribute("likeCount", likeCount);

        // 关注数量
        long followeeCount = followService.findFolloweeCount(userId, ENTITY_TYPE_USER);
        model.addAttribute("followeeCount", followeeCount);
        // 粉丝数量
        long followerCount = followService.findFollowerCount(ENTITY_TYPE_USER, userId);
        model.addAttribute("followerCount", followerCount);
        // 是否已关注
        boolean hasFollowed = false;
        if (hostHolder.getUser() != null) {
            hasFollowed = followService.hasFollowed(hostHolder.getUser().getId(), ENTITY_TYPE_USER, userId);
        }
        model.addAttribute("hasFollowed", hasFollowed);

        return "/site/profile";

    }



}
